package controller

import (
	"context"
	"fmt"
	"parking-lot-go-push/controller/parknfly"
	"parking-lot-go-push/controller/xiaoqiang"
	"parking-lot-go-push/logger"
	"parking-lot-go-push/model"
	"parking-lot-go-push/model/cars"
	"parking-lot-go-push/mongodb"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var outLogger = logger.NewLogger("out", "error")

func Out() {

	//tag查询
	ctx := context.TODO()
	var carsOutMongoDb mongodb.CarsOutMongoDbStruct

	collection := model.MongoDb.Collection(carsOutMongoDb.MongoDBTableName())
	cur, err := collection.Find(ctx, bson.M{
		"push_status": 0,
		"push_err_num": bson.M{
			"$lte": 5,
		},
		"push_time": bson.M{
			"$lte": time.Now().Unix(),
		},
	}, options.Find().SetSort(bson.D{{"out_time", 1}}))
	if err != nil {
		outLogger.Error(fmt.Sprintf("出场记录查询失败:%s", err.Error()))
		return
	}
	defer cur.Close(ctx)

	var outData []mongodb.CarsOutMongoDbStruct

	for cur.Next(ctx) {
		var out mongodb.CarsOutMongoDbStruct
		if err := cur.Decode(&out); err != nil {
			outLogger.Error(fmt.Sprintf("标签:解码出场数据失败:%s", err.Error()))
			return
		}
		outData = append(outData, out)
	}

	if len(outData) == 0 {
		outLogger.Info("没有需要处理的数据")
	}

	for _, v := range outData {
		outLogger.Info(fmt.Sprintf("推送车牌:%s,订单类型:%d", v.CarNumber, v.OrderType))

		switch v.OrderType {
		case 0: //如之停车
			var carsOutStruct cars.CarsOutStruct
			if err := carsOutStruct.PushSuccess(v.OrderNo, v.OutTime, 2, map[string]interface{}{
				"carId": v.CarNumber,
			}); err != nil {
				outLogger.Info(fmt.Sprintf("如之停车更新订单状态失败,车牌:%s,颜色:%d", v.CarNumber, v.CarNoColor))
			}
		case 1: //小强
			var xiaoQiangOut xiaoqiang.OutStruct
			xiaoQiangOut.CarsOutMongoDbStruct = v
			xiaoQiangOut.Out()
		case 2: //泊安飞
			var parknflyOut parknfly.OutStruct
			parknflyOut.CarsOutMongoDbStruct = v
			parknflyOut.Out()
		case 3: //钉钉
			if err := CurlPostJson("push/out", map[string]interface{}{
				"park_name":    v.ParkName,
				"car_number":   v.CarNumber,
				"car_no_color": v.CarNoColor,
				"region_name":  v.RegionName,
				"out_time":     v.OutTime,
				"money":        v.ParkAmt,
				"stop_time":    v.ParkTime,
			}); err != nil {
				outLogger.Info(fmt.Sprintf("钉钉进场推送出败,车牌:%s,颜色:%d", v.CarNumber, v.CarNoColor))
			} else {
				//成功状态更新
				var carsOutStruct cars.CarsOutStruct
				if err := carsOutStruct.PushSuccess(v.OrderNo, v.OutTime, 2, map[string]interface{}{
					"carId": v.CarNumber,
				}); err != nil {
					outLogger.Info(fmt.Sprintf("钉钉更新订单状态失败,车牌:%s,颜色:%d", v.CarNumber, v.CarNoColor))
				}
			}
		}
	}

}
